import {defineStore} from 'pinia';
import {usePermissionStore} from '@/store';
import type {UserInfo} from '@/types/interface';
import {currentUser, loginPwd} from "@/api/login";

const InitUserInfo: UserInfo = {
	name: '', // 用户名，用于展示在页面右上角头像处
	roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
};

export const useUserStore = defineStore('user', {
	state: () => ({
		token: 'main_token', // 默认token不走权限
		tokenHead: 'Authorization', // 请求头
		userInfo: { ...InitUserInfo },
	}),
	getters: {
		roles: (state) => {
			return state.userInfo?.roles;
		},
	},
	actions: {
		async login(userInfo: Record<string, unknown>) {
            const { token, tokenHead } = await loginPwd(userInfo);
            this.token = token;
            this.tokenHead = tokenHead;
		},
		async getUserInfo() {
            this.userInfo = await currentUser();
            const permissionStore = usePermissionStore();
            permissionStore.getPerms();
		},
		async logout() {
			this.token = '';
			this.userInfo = { ...InitUserInfo };
		},
	},
	persist: {
		afterRestore: () => {
			const permissionStore = usePermissionStore();
			permissionStore.initRoutes();
		},
		key: 'user',
		paths: ['token'],
	},
});
